import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Form,
  Input,
  Upload,
  DatePicker,
  message,
  Select,
  Switch,
  InputNumber,
} from 'antd';
import moment from 'moment';
import E from 'wangeditor';
import { format } from 'prettier';

const {
  uTypeList,
  uBusinessManageAdd,
  uBusinessManageUpdate,
  addReciver,
  uTopList,
} = api;

const { Option } = Select;

let editor: any = null;
let editor2: any = null;
export default (props: any) => {
  const [form] = Form.useForm();
  // form.setFieldsValue()

  const { manageId, schoolId } = JSON.parse(sessionStorage.info).userInfo;
  const isAdd = props.history.location.state.isAdd;
  const { initData, userName, businessManageId } = props.history.location.state;
  const [content, setContent] = useState('');
  const [content2, setContent2] = useState('');
  // 商家类型列表
  const [typeList, setTypeList] = useState([]);
  const [topList, setTopList] = useState([]);
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 4, span: 16 },
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  const [fileList1, seFileList1]: any = useState([]);
  const [fileList2, seFileList2]: any = useState([]);
  const onchange1 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList1].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList1(list);
    } else {
      seFileList1(fileLists);
    }
  };
  const onchange2 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList2].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList2(list);
    } else {
      seFileList2(fileLists);
    }
  };
  // 格式化商家类型
  const formatType = (arr: any, attr: any) => {
    const arrReturn = arr.filter((item: any) => item.id === attr);
    return arrReturn.length ? arrReturn[0] : [];
  };

  const onFinish = (v: any) => {
    if (fileList1.length && fileList2.length && editor.txt.html()) {
      let srcs = '';
      fileList1.map((item: any) => {
        srcs += `${item.url}&`;
      });
      srcs = srcs.slice(0, -1);

      let srcs2 = '';
      fileList2.map((item: any) => {
        srcs2 += `${item.url}&`;
      });
      srcs2 = srcs2.slice(0, -1);
      const {
        title,
        uType,
        tel,
        address,
        endTime,
        businessTime,
        openid,
        scale,
        wxName,
        topNum,
        ord,
      } = v;
      const params = {
        manageId,
        uSchoolId: schoolId,
        title,
        uTypeId: uType,
        uType: formatType(typeList, uType).uType,
        uSubType: formatType(typeList, uType).uSubType,
        tel,
        address,
        endTime: lhTool.formatDate.format(
          new Date(endTime),
          'yyyy-MM-dd hh:mm:ss',
        ),
        businessTime,
        buyNotice: editor.txt.html(),
        detail: editor2.txt.html(),
        src: srcs,
        url: srcs2,
        openid,
        scale,
        wxName,
        topNum,
        ord,
      };
      if (isAdd) {
        uBusinessManageAdd({ ...params, userName, businessManageId }).then(
          _ => {
            addReciver({
              wxName,
              openid,
            }).then(_ => {
              props.history.push({
                pathname: '/businessManage',
              });
            });
          },
        );
      } else {
        uBusinessManageUpdate({ ...params, id: initData.id }).then(res => {
          addReciver({
            wxName,
            openid,
          }).then(_ => {
            props.history.push({
              pathname: '/businessManage',
            });
          });
        });
      }
    } else {
      if (!fileList1.length) {
        message.error('请上传详情图片');
      }
      if (!fileList2.length) {
        message.error('请上传列表图片');
      }
      if (!editor.txt.html()) {
        message.error('请编写活动详情');
      }
    }
  };

  const getTypeList = () => {
    uTypeList().then(res => {
      setTypeList(res.data);
    });
    uTopList({
      uSchoolId: schoolId,
    }).then(res => {
      res.data.unshift({
        id: 0,
        name: '非爆款区',
      });
      setTopList(res.data);
    });
  };
  // const disabledDate = (e: any) => {
  //   const end = new Date(initData.time).getTime() + 30 * 24 * 60 * 60 * 1000;
  //   const now = new Date().getTime()
  //   console.log(now-end/24 * 60 * 60 * 1000)
  //   return now > end;
  // };

  useEffect(() => {
    getTypeList();

    // 富文本1
    editor = new E('#edit');
    editor.config.uploadImgServer = `${process.env.apiUrl}upload/edit`;
    editor.config.showFullScreen = false;
    editor.config.onchange = (newHtml: any) => {
      setContent(newHtml);
    };
    editor.create();

    // 富文本2
    editor2 = new E('#edit2');
    editor2.config.uploadImgServer = `${process.env.apiUrl}upload/edit`;
    editor2.config.showFullScreen = false;
    editor2.config.onchange = (newHtml: any) => {
      setContent2(newHtml);
    };
    editor2.create();

    if (!isAdd) {
      const arr1: any = [];
      const arr2: any = [];
      initData.src.split('&').map((item: any, i: any) => {
        arr1.push({
          uid: i,
          url: item,
        });
      });
      initData.url.split('&').map((item: any, i: any) => {
        arr2.push({
          uid: i,
          url: item,
        });
      });
      seFileList1(arr1);
      seFileList2(arr2);
      editor.txt.html(initData.buyNotice);
      editor2.txt.html(initData.detail);
    }
    return () => {
      // editor.destroy();
      // editor2.destroy()
    };
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <Form
          className={styles.form}
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            label="商家微信号openid"
            name="openid"
            rules={[{ required: true, message: '商家微信号openid' }]}
            initialValue={isAdd ? '' : initData.openid}
          >
            <Input placeholder="请联系商家在U你校园小程序中获取" />
          </Form.Item>
          <Form.Item
            label="商家微信认证姓名"
            name="wxName"
            rules={[{ required: true, message: '商家微信认证姓名' }]}
            initialValue={isAdd ? '' : initData.wxName}
          >
            <Input placeholder="商家微信认证姓名" />
          </Form.Item>
          <Form.Item
            label="商家分账比例"
            name="scale"
            rules={[{ required: true, message: '商家分账比例' }]}
            initialValue={isAdd ? '' : initData.scale}
          >
            <InputNumber
              placeholder="1-95之间的整数"
              step={1}
              style={{ width: 300 }}
              min={1}
              max={95}
            />
          </Form.Item>
          <Form.Item
            label="商家标题"
            name="title"
            rules={[{ required: true, message: '请输入商家标题' }]}
            initialValue={isAdd ? '' : initData.title}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            label="商家类型"
            name="uType"
            rules={[{ required: true, message: '请选择商家类型' }]}
            initialValue={isAdd ? '' : initData.uTypeId}
          >
            <Select
              showSearch
              style={{ width: 300 }}
              placeholder="请选择..."
              allowClear
            >
              {typeList.map((item: any, i: any) => (
                <Option key={i} value={item.id}>
                  {item.name + '----' + item.subName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="爆款区"
            name="topNum"
            rules={[{ required: true, message: '请选择爆款区类型' }]}
            initialValue={isAdd ? '' : initData.topNum}
          >
            <Select
              showSearch
              style={{ width: 300 }}
              placeholder="请选择..."
              allowClear
            >
              {topList.map((item: any, i: any) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="爆款区排序"
            name="ord"
            rules={[{ required: true, message: '爆款区排序' }]}
            initialValue={isAdd ? '' : initData.ord}
          >
            <InputNumber
              placeholder="非负数，值越大排序越靠前"
              step={1}
              style={{ width: 300 }}
              min={0}
            />
          </Form.Item>
          <Form.Item
            label="商家列表图片（单张）"
            name="url"
            rules={[{ required: false, message: '商家列表图片（单张）' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList2}
              // onPreview={this.handlePreview}
              onChange={onchange2}
            >
              {fileList2.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            label="商家详情图片（多张）"
            name="src"
            rules={[{ required: false, message: '商家详情图片（多张）' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList1}
              // onPreview={this.handlePreview}
              onChange={onchange1}
            >
              {fileList1.length >= 6 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            label="商家电话"
            name="tel"
            rules={[{ required: true, message: '请输入商家电话' }]}
            initialValue={isAdd ? '' : initData.tel}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商家地址"
            name="address"
            rules={[{ required: true, message: '请输入商家地址' }]}
            initialValue={isAdd ? '' : initData.address}
          >
            <Input />
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : moment(new Date(initData.endTime))}
            label="商家活动结束时间"
            name="endTime"
            rules={[{ required: true, message: '请选择商家活动结束时间' }]}
          >
            <DatePicker
              style={{ position: 'relative', zIndex: 10000 }}
              showTime
              format="YYYY-MM-DD HH:mm"
              // disabledDate={disabledDate}
            />
          </Form.Item>
          <Form.Item
            label="商家营业时间"
            name="businessTime"
            rules={[{ required: true, message: '商家营业时间' }]}
            initialValue={isAdd ? '' : initData.businessTime}
          >
            <Input />
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : initData.buyNotice}
            label="商家购买须知"
            name="buyNotice"
            rules={[{ required: false, message: '请输入商家购买须知' }]}
          >
            <div style={{ position: 'relative', zIndex: 1 }} id="edit"></div>
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : initData.detail}
            label="商品详情"
            name="detail"
            rules={[{ required: false, message: '请输入商品详情' }]}
          >
            <div id="edit2"></div>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </CardCommon>
  );
};
